const express = require('express');
const router = express.Router();
const Site = require('../models/Site');
const Content = require('../models/Content');
const { auth } = require('../middleware/auth');

// 获取所有站点
router.get('/', auth, async (req, res) => {
  try {
    const { page = 1, limit = 10, status } = req.query;
    const offset = (page - 1) * limit;
    
    const where = {};
    if (status) where.status = status;
    
    const sites = await Site.findAndCountAll({
      where,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });
    
    res.json({
      sites: sites.rows,
      pagination: {
        total: sites.count,
        page: parseInt(page),
        limit: parseInt(limit),
        pages: Math.ceil(sites.count / limit)
      }
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 创建站点
router.post('/', auth, async (req, res) => {
  try {
    const { name, domain, subdomain, template, config } = req.body;
    
    // 验证域名唯一性
    const existingSite = await Site.findOne({ where: { domain } });
    if (existingSite) {
      return res.status(400).json({ error: '域名已存在' });
    }
    
    const site = await Site.create({
      name,
      domain,
      subdomain,
      template: template || 'default',
      config: config || {}
    });
    
    res.status(201).json(site);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取单个站点
router.get('/:id', auth, async (req, res) => {
  try {
    const site = await Site.findByPk(req.params.id);
    if (!site) {
      return res.status(404).json({ error: '站点不存在' });
    }
    
    res.json(site);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 更新站点
router.put('/:id', auth, async (req, res) => {
  try {
    const site = await Site.findByPk(req.params.id);
    if (!site) {
      return res.status(404).json({ error: '站点不存在' });
    }
    
    const { name, template, status, config, seoConfig } = req.body;
    
    await site.update({
      name,
      template,
      status,
      config,
      seoConfig
    });
    
    res.json(site);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除站点
router.delete('/:id', auth, async (req, res) => {
  try {
    const site = await Site.findByPk(req.params.id);
    if (!site) {
      return res.status(404).json({ error: '站点不存在' });
    }
    
    // 检查是否有内容
    const contentCount = await Content.count({ where: { siteId: site.id } });
    if (contentCount > 0) {
      return res.status(400).json({ error: '站点下有内容，无法删除' });
    }
    
    await site.destroy();
    res.json({ message: '站点删除成功' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取站点统计
router.get('/:id/stats', auth, async (req, res) => {
  try {
    const siteId = req.params.id;
    
    const [contentCount, publishedCount, draftCount] = await Promise.all([
      Content.count({ where: { siteId } }),
      Content.count({ where: { siteId, status: 'published' } }),
      Content.count({ where: { siteId, status: 'draft' } })
    ]);
    
    res.json({
      totalContent: contentCount,
      publishedContent: publishedCount,
      draftContent: draftCount
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;
